<template>
  <view class="container">
    <!-- 头部 -->
    <view class="header">
      <text class="title">视频学习</text>
      <view class="points">
        <uni-icons type="coin" size="16" color="#4a90e2" />
        <text>积分：{{ user.points || 0 }}</text>
      </view>
    </view>

    <!-- 分类筛选 -->
    <view class="category-filter">
      <view 
        v-for="category in categories" 
        :key="category.value" 
        class="category-item"
        :class="{ active: selectedCategory === category.value }"
        @click="selectCategory(category.value)"
      >
        <text>{{ category.label }}</text>
      </view>
    </view>

    <!-- 视频列表 -->
    <scroll-view scroll-y class="video-list">
      <view v-if="loading" class="loading">
        <uni-icons type="spinner" size="24" color="#4a90e2" />
        <text>加载中...</text>
      </view>
      <view v-else-if="videos.length === 0" class="empty">
        <text>暂无匹配的视频</text>
      </view>
      <view v-else v-for="video in videos" :key="video.id" class="video-card">
        <text class="video-title">{{ video.title }}</text>
        <text class="video-category">{{ video.category_label }}</text>
        <video
          :id="'video-' + video.id"
          :src="video.url"
          controls
          @ended="onVideoEnded(video.id, video.duration)"
          @timeupdate="onTimeUpdate(video.id)"
          @pause="saveProgress(video.id)"
          class="video-player"
          :initial-time="video.progress || 0"
        ></video>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      user: {},
      videos: [],
      categories: [
        { label: '全部', value: '' },
        { label: '数学', value: 'math' },
        { label: '语文', value: 'chinese' },
        { label: '英语', value: 'english' }
      ],
      selectedCategory: '',
      searchKeyword: '',
      loading: false,
      debounceTimer: null
    };
  },
  onLoad() {
    this.loadUserData();
    this.loadVideos();
    this.loadCategories();
  },
  onShow() {
    this.getUserPoints();
  },
  methods: {
    // 加载用户信息
    loadUserData() {
      this.user = uni.getStorageSync('user') || {};
      if (!this.user.id) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        uni.navigateTo({ url: '/pages/student/login' });
      }
    },

    // 获取用户积分
    async getUserPoints() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserPoints',
          data: { action: 'get', user_id: this.user.id }
        });
        if (res.result.code === 0) {
          this.user.points = res.result.data.points;
        } else {
          uni.showToast({ title: res.result.msg, icon: 'none' });
        }
      } catch (e) {
        console.error('获取积分失败:', e);
        uni.showToast({ title: '网络错误', icon: 'none' });
      }
    },

    // 加载分类
    async loadCategories() {
      try {
        const res = await uniCloud.callFunction({
          name: 'categoryManage',
          data: { action: 'get' }
        });
        if (res.result.code === 0) {
          this.categories = [{ label: '全部', value: '' }, ...res.result.data];
        } else {
          uni.showToast({ title: res.result.msg, icon: 'none' });
        }
      } catch (e) {
        console.error('获取分类失败:', e);
        uni.showToast({ title: '加载分类失败', icon: 'none' });
      }
    },

    // 加载视频列表
    async loadVideos() {
      this.loading = true;
      try {
        const res = await uniCloud.callFunction({
          name: 'videoManage',
          data: { 
            action: 'get',
            category: this.selectedCategory,
            keyword: this.searchKeyword,
            user_id: this.user.id
          }
        });
        if (res.result.code === 0) {
          this.videos = res.result.data.map(video => ({
            ...video,
            progress: video.progress || 0
          }));
        } else {
          uni.showToast({ title: res.result.msg, icon: 'none' });
        }
      } catch (e) {
        console.error('获取视频列表失败:', e);
        uni.showToast({ title: '加载视频失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    },

    // 选择分类
    selectCategory(category) {
      this.selectedCategory = category;
      this.loadVideos();
    },

    // 搜索防抖
    debounceSearch() {
      clearTimeout(this.debounceTimer);
      this.debounceTimer = setTimeout(() => {
        this.loadVideos();
      }, 500);
    },

    // 视频播放结束
    async onVideoEnded(video_id, duration) {
      try {
        const res = await uniCloud.callFunction({
          name: 'videoManage',
          data: {
            action: 'watch',
            user_id: this.user.id,
            video_id,
            watch_time: duration,
            duration
          }
        });
        if (res.result.code === 0 && res.result.data.points > 0) {
          uni.showToast({ title: `观看完成，获得 ${res.result.data.points} 积分`, icon: 'success' });
          this.getUserPoints();
          this.videos = this.videos.map(video => 
            video.id === video_id ? { ...video, progress: 0 } : video
          );
        } else {
          uni.showToast({ title: res.result.msg, icon: 'none' });
        }
      } catch (e) {
        console.error('记录观看失败:', e);
        uni.showToast({ title: '记录观看失败', icon: 'none' });
      }
    },

    // 播放进度更新
    onTimeUpdate(video_id) {
      const videoElement = uni.createSelectorQuery()
        .select(`#video-${video_id}`)
        .node()
        .exec(res => {
          if (res[0] && res[0].node) {
            const currentTime = Math.floor(res[0].node.currentTime);
            this.videos = this.videos.map(video => 
              video.id === video_id ? { ...video, progress: currentTime } : video
            );
          }
        });
    },

    // 保存播放进度
    async saveProgress(video_id) {
      const video = this.videos.find(v => v.id === video_id);
      if (!video || video.progress <= 0) return;

      try {
        const res = await uniCloud.callFunction({
          name: 'videoManage',
          data: {
            action: 'saveProgress',
            user_id: this.user.id,
            video_id,
            progress: video.progress
          }
        });
        if (res.result.code !== 0) {
          console.error('保存进度失败:', res.result.msg);
        }
      } catch (e) {
        console.error('保存进度失败:', e);
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 16px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 头部 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title {
  font-size: 22px;
  font-weight: 600;
  color: #1a1a1a;
}

.points {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #4a90e2;
}

/* 搜索框 */
.search-bar {
  display: flex;
  align-items: center;
  background: #fff;
  border-radius: 12px;
  padding: 8px 12px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-input {
  flex: 1;
  font-size: 14px;
  color: #1a1a1a;
  margin-left: 8px;
  border: none;
  background: transparent;
}

/* 分类筛选 */
.category-filter {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.category-item {
  padding: 8px 16px;
  border-radius: 16px;
  background: #e5e7eb;
  font-size: 14px;
  color: #555;
  transition: all 0.3s;
}

.category-item.active {
  background: #4a90e2;
  color: #fff;
}

/* 视频列表 */
.video-list {
  height: calc(100vh - 220px);
}

.video-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.video-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 8px;
}

.video-category {
  font-size: 12px;
  color: #555;
  margin-bottom: 12px;
}

.video-player {
  width: 100%;
  height: 200px;
  border-radius: 8px;
}

/* 加载状态 */
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 24px;
  color: #4a90e2;
}

/* 空状态 */
.empty {
  text-align: center;
  font-size: 14px;
  color: #555;
  padding: 24px;
}
</style>